<?php

namespace App\Http\Controllers;

use App\Models\ForeignSpeakerCollection;
use App\Models\ForeignSpeakerCollectionPivot;
use App\Models\Links;
use App\Models\Project;
use App\Models\ProjectMeetingInvitationSpeaker;
use App\Models\SmsLog;
use App\Models\Speaker;
use App\Models\User;
use App\Models\UserCollection;
use App\Services\GuestSpeakersService;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;

class SpeakerController extends BaseController
{

    public function speakerList(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('page', 'limit', 'global_search');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $model = new Speaker();

        $list = $model->getGuestSpeakerList((int) $payload['page'], (int) $payload['limit'], $payload, userId());
        $userId = userId();
        $follow_ids = [];
        $partner_ids = [];
        if (!empty($userId)) {
            $follow_ids = UserCollection::getMemberListById(['user_id' => $userId, 'type' => 8]);
            // 获取用户参与的项目
            $project_ids = Project::where(['user_id' => $userId, 'project_status' => 2])->pluck('id');
            // 根据已完成项目查找合作过的讲者
            $partner_ids = ProjectMeetingInvitationSpeaker::whereIn('project_id', $project_ids)
                ->where('invitation_status', 1)
                ->pluck('speaker_id');
            if (!empty($partner_ids)) {
                $partner_ids = $partner_ids->toArray();
            }
        }

        $list = infoArray($list, $follow_ids, []);
        $list = partner($list, $partner_ids);
        return successPaginate($list);
    }

    /**
     * 外讲列表-无分页，全
     * @todo 后期修改，现在字段不清晰
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-22
     * @param Request $request
     * @return void
     */
    public function speakerLists(Request $request)
    {
        $payload = $request->only('global_search');

        $model = new Speaker();

        $list = $model->getGuestSpeakerLists($payload);

        $follow_ids = [];
        $partner_ids = [];
        $userId = userId();
        if (!empty($userId)) {
            $follow_ids = UserCollection::getMemberListById(['user_id' => $userId, 'type' => 8]);
            // 获取用户参与的项目
            $project_ids = Project::where(['user_id' => $userId, 'project_status' => 2])->pluck('id');
            // 根据已完成项目查找合作过的讲者
            $partner_ids = ProjectMeetingInvitationSpeaker::whereIn('project_id', $project_ids)
                ->where('invitation_status', 1)
                ->pluck('speaker_id');
            if (!empty($partner_ids)) {
                $partner_ids = $partner_ids->toArray();
            }
        }
        $list = infoArray($list, $follow_ids, []);
        $list = partner($list, $partner_ids);
        return success($list);

        // return successPaginate($list);
    }


    /**
     * 外籍讲者详情
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-11
     * @param Request $request
     * @return void
     */
    public function guestSpeakerDetail(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $follow_ids = [];
        $partner_ids = [];
        $detail = Speaker::find($payload['id'])->toArray();
        // $detail = Speaker::find([1103, 1102])->toArray();

        $userId = userId();
        if (!empty($userId)) {
            $follow_ids = UserCollection::getMemberListById(['user_id' => $userId, 'type' => 8]);
            // 获取用户参与的项目
            $project_ids = Project::where(['user_id' => $userId, 'project_status' => 2])->pluck('id');
            // 根据已完成项目查找合作过的讲者
            $partner_ids = ProjectMeetingInvitationSpeaker::whereIn('project_id', $project_ids)
                ->where('invitation_status', 1)
                ->pluck('speaker_id');
            if (!empty($partner_ids)) {
                $partner_ids = $partner_ids->toArray();
            }
        }

        // dd($detail, count($detail));
        if (is_1d_or_2d_array($detail) == '2') {
            $detail = infoArray($detail, $follow_ids);
            $detail = partner($detail, $partner_ids);
        } elseif (is_1d_or_2d_array($detail) == '1') {

            if (in_array($detail['id'], $follow_ids)) {
                $detail['is_follow'] = 1;
            } else {
                $detail['is_follow'] = 0;
            }

            if (in_array($detail['id'], $partner_ids)) {
                $detail['is_partner'] = 1;
            } else {
                $detail['is_partner'] = 0;
            }
        }

        return success($detail);
    }



    /**
     * 查看分享合集内的专家详情(不需要登录)
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-11
     * @param Request $request
     * @return void
     */
    public function guestSpeakerDetail2(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(Speaker::find($payload['id']));
    }



    /**
     * 外籍讲者集合列表(我的合集列表)
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-11
     * @param Request $request
     * @return json
     */
    public function speakerCollectionList(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('page', 'limit', 'share_collection_id', 'userId', 'name');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $model = new ForeignSpeakerCollection(); //ForeignSpeakerCollection
        $userId = userId();
        if (isset($payload['share_collection_id']) && !empty($payload['share_collection_id'])) {

            GuestSpeakersService::getInstance()->acceptInvitaion(Arr::only($payload, ['share_collection_id', 'userId']), (int) $userId);
        }

        $list = $model->getCollectionList((int) $payload['page'], (int) $payload['limit'], ['user_id' => $userId, 'name' => $payload['name']]);

        if ($list->count()) {
            foreach ($list as $key => &$val) {
                $val['count'] = ForeignSpeakerCollectionPivot::where('collection_id', $val['id'])->count();
                $val['share'] = ($val['user_id'] ==  $userId) ? 0 : 1;
            }
        }

        return successPaginate($list ?? []);

        // return success();
    }


    /**
     * 外籍讲者集合列表(我的合集列表)无分页
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-11
     * @param Request $request
     * @return json
     */
    public function collectionList(Request $request)
    {
        $model = new ForeignSpeakerCollection();
        $userId = userId();
        return success($model->getCollectionCateList(['user_id' => $userId]));
    }


    /**
     * 创建或修改集合
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-16
     * @param Request $request
     * @return void
     */
    public function createOrUpdateCollection(Request $request)
    {
        $rules = [
            'name' => ['required'],
        ];

        $message = [
            'name.required' => '集合名称不能为空',
        ];

        $payload = $request->only('name', 'id', 'photo');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $userId = userId();
        $result = GuestSpeakersService::getInstance()->updateOrCreateCollection(['id' => $payload['id'], 'user_id' => $userId], ['name' => $payload['name'], 'photo' => $payload['photo'], 'user_id' => $userId, 'status' => 1]);
        if ($result) {
            return success();
        } else {
            return fail_message();
        }
    }


    /**
     * 提交外籍讲者id到集合当中
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-16
     * @param Request $request
     * @return void
     */
    public function putIdToCollection(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'speaker_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
            'speaker_id.required' => '请选择讲者',
        ];

        $payload = $request->only('collection_id', 'speaker_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        // @todo 方便测试把speaker_id 字符串转数组，后期删除转换操作
        // $payload['speaker_id'] = explode(',', $payload['speaker_id']);
        return success(GuestSpeakersService::getInstance()->createCollectionDetail($payload, userId()));
    }

    /**
     * 删除集合当中的外籍讲者
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return void
     */
    public function deleteCollectionSpeaker(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'speaker_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
            'speaker_id.required' => '请选择讲者',
        ];

        $payload = $request->only('collection_id', 'speaker_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        return success(GuestSpeakersService::getInstance()->deleteCollectionDetail($payload, (int) userId()));
    }



    /**
     * 删除集合
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return void
     */
    public function deleteCollection(Request $request)
    {
        $rules = [
            'id' => ['required'],
        ];

        $message = [
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        return success(GuestSpeakersService::getInstance()->deleteCollection((int) $payload['id']));
    }



    /**
     * 集合详情列表 分享合集详情列表  不需要登录
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return void
     */
    public function collectionDetailList2(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
            'page.required' => '缺少参数页码',
            'limit.required' => '缺少参数限制条数',
        ];

        $payload = $request->only('collection_id', 'page', 'limit', 'name');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        if (is_numeric($payload['collection_id'])) {
            $surveyId = $payload['collection_id'];
        } else {
            $surveyId = stringToId($payload['collection_id']);
        }
        $model = new ForeignSpeakerCollection();
        $list = $model->getCollectionListById((int) $surveyId, (int) $payload['page'], (int) $payload['limit'], ['name' => $payload['name']]);
        // 获取用id
        $userId = userId();
        // 获取用户参与的项目
        $project_ids = Project::where(['user_id' => $userId, 'project_status' => 2])->pluck('id');
        if (!empty($project_ids)) {
            // 根据已完成项目查找合作过的讲者ProjectMeetingInvitationSpeaker
            $partner_ids = ProjectMeetingInvitationSpeaker::whereIn('project_id', $project_ids)
                ->where('invitation_status', 1)
                ->pluck('speaker_id');
            if (!empty($partner_ids)) {
                $partner_ids = $partner_ids->toArray();
            }
        }
        // 默认都是他人的合集
        $list['is_other'] = 1;
        // 查询是不是自己的合集
        $userCollection = $model->where('id', $surveyId)->where('user_id', $userId)->first();
        if (!empty($userCollection)) {
            // 如果是自己的合集，修改状态为0
            $list['is_other'] = 0;
        }


        $list['list'] = partner($list['list'], $partner_ids);
        return success($list);
    }


    /**
     * 集合详情列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return void
     */
    public function collectionDetailList(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
            'page.required' => '缺少参数页码',
            'limit.required' => '缺少参数限制条数',
        ];

        $payload = $request->only('collection_id', 'page', 'limit', 'name');

        $validator = Validator::make($payload, $rules, $message);
        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        if (is_numeric($payload['collection_id'])) {
            $surveyId = $payload['collection_id'];
        } else {
            $surveyId = stringToId($payload['collection_id']);
        }

        $model = new ForeignSpeakerCollection();
        $list = $model->getCollectionListById((int) $surveyId, (int) $payload['page'], (int) $payload['limit'], ['name' => $payload['name']]);

        // 获取用户参与的项目
        $project_ids = Project::where(['user_id' => userId(), 'project_status' => 2])->pluck('id');
        // 根据已完成项目查找合作过的讲者ProjectMeetingInvitationSpeaker
        $partner_ids = ProjectMeetingInvitationSpeaker::whereIn('project_id', $project_ids)
            ->where('invitation_status', 1)
            ->pluck('speaker_id');
        if (!empty($partner_ids)) {
            $partner_ids = $partner_ids->toArray();
        }

        $list['list'] = partner($list['list'], $partner_ids);
        return success($list);
    }



    /**
     * 分享集合
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return void
     */
    public function shareCollection(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
        ];

        $payload = $request->only('collection_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(GuestSpeakersService::getInstance()->shareCollection((int) $payload['collection_id']));
    }

    /**
     * 判断是否是第一次
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-14
     * @param Request $request
     * @return json
     */
    public function isFirstForTime(Request $request)
    {
        $model = new ForeignSpeakerCollection();
        $userId = userId();
        // if (empty($userId)) {
        //     return fail_message('请先登录');
        // }
        return success($model->isFirst(['user_id' => $userId]));
    }


    /**
     * 集合内推荐外籍讲者
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-06-20
     * @param Request $request
     * @return void
     */
    public function recommendSpeaker(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'speaker_id' => ['required'],
            'recommend_id' => ['required'],
            // 'argument' => ['required'],
        ];

        $message = [
            'collection_id.required' => '缺少集合ID',
            'speaker_id.required' => '缺少讲者ID',
            'recommend_id.required' => '请选择推荐顺序',
            // 'argument.required' => '缺少推荐理由',
        ];

        $payload = $request->only('collection_id', 'speaker_id', 'recommend_id', 'argument');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(GuestSpeakersService::getInstance()->recommendSpeaker($payload));
    }

    /**
     * 集合内点赞外籍讲者
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-06-20
     * @param Request $request
     * @return void
     */

    public function giveLikeSpeaker(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'speaker_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
            'speaker_id.required' => '缺少讲者ID',
        ];

        $payload = $request->only('collection_id', 'speaker_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(GuestSpeakersService::getInstance()->giveLikeSpeaker($payload));
    }

    /**
     * 集合内取消点赞外籍讲者
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-06-20
     * @param Request $request
     * @return void
     */

    public function CancelGiveLikeSpeaker(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
            'speaker_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
            'speaker_id.required' => '缺少讲者ID',
        ];

        $payload = $request->only('collection_id', 'speaker_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        return success(GuestSpeakersService::getInstance()->CancelGiveLikeSpeaker($payload));
    }


    /**
     * 复制合集到自己的账户下
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-16
     * @param Request $request
     * @return void
     */
    public function replicateSpeakerCollection(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '缺少主要参数合集ID',
        ];

        $payload = $request->only('collection_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        if (is_numeric($payload['collection_id'])) {
            $surveyId = $payload['collection_id'];
        } else {
            $surveyId = stringToId($payload['collection_id']);
        }

        $userid = userId();
        $data = ForeignSpeakerCollection::where(['collection_id' => $surveyId, 'user_id' => $userid])->first();

        if (!empty($data)) {
            return fail_message('合集已存在，无需重复保存');
        }


        return success(GuestSpeakersService::getInstance()->replicateSpeaker($surveyId, $userid));
    }



    /**
     * 关注、取消关注
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-24
     * @param Request $request
     * @return json
     */
    public function follow(Request $request)
    {

        $rules = [
            'info_id' => ['required'],
            'type_id' => ['required'],
            'status' => ['required'],
        ];

        $message = [
            'info_id.required' => '信息库id不能为空',
            'type_id.required' => '分类id不能为空',
            'status.required' => '状态不能为空',
        ];

        $payload = $request->only('info_id', 'type_id', 'status');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $info = UserCollection::where('user_id', userId())->where('info_id', $payload['info_id'])->where('type', $payload['type_id'])->first();

        if ($info) {
            $info->status = $payload['status'];
            $info->save();
            return success_message('操作成功');
        } else {
            UserCollection::create([
                'user_id' => userId(),
                'info_id'   => $payload['info_id'],
                'type'  => $payload['type_id'],
                'status'    => 1,
            ]);
            return success_message('关注成功');
        }
    }


    /**
     * url重定向
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-08-24
     * @param Request $request
     * @return void
     */
    public function urlRedirect(Request $request)
    {
        $where = function ($query) use ($request) {
            if ($request->only('keyword')) {
                $query->where('keyword', $request->only('keyword'));
            }
            $platform = $request->only('platform');
            if (isset($platform) && !empty($platform)) {
                $query->where('platform', $platform);
            }
        };
        $redirect_url = Links::where($where)->first();
        if (!empty($redirect_url)) {
            return redirect()->away($redirect_url['long_url']);
        }
    }



    public function getWechatConfig(Request $request)
    {
        $url = $request->input('url');
        if (empty($url)) {
            return fail_message('缺少参数');
        }

        // 海迈德医学服务号appid   appsecret
        $config = [
            'app_id' => 'wx36a42a0291c7c236',
            'secret' => '09800f27d559122e79fa8463d0c2568f',

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $app = Factory::officialAccount($config);
        noticeLog('share url : ' . $url);
        $app->jssdk->setUrl($url);
        $success = $app->jssdk->buildConfig(
            [
                'updateAppMessageShareData',
                'updateTimelineShareData',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
            ],
            false
        );
        noticeLog('app jssdk : ' . $success);
        // noticeLog('app jssdk : ' . json_decode($success, true));
        return success(json_decode($success, true));
    }
}
